<!-- 角色编辑弹窗 -->
<template>
  <div>
    <el-drawer :visible="drawerEditBoolen"
               size="50%"
               :before-close="handleClose"
               ref="drawer">
      <template v-slot:title>
        <span class="hLabel">{{ isUpdate ? '修改分类' : '添加分类' }}</span>
      </template>
      <div class="ele-body">
        <el-card shadow="never">
          <div class="flex-column-between height83">
            <el-form ref="form"
                     :model="form"
                     :rules="rules"
                     label-width="100px">
              <el-form-item label="分类名称:"
                            prop="classificationName">
                <el-input clearable
                          :maxlength="100"
                          v-model="form.classificationName"
                          placeholder="请输入分类名称">
                </el-input>
              </el-form-item>

              <el-form-item label="排序值:"
                            prop="sortByCategory">
                <span slot="label">
                  排序值
                  <el-tooltip placement="top">
                    <div slot="content">
                      用于前端展示排序， 值越大排在前面
                    </div>
                    <i class="el-icon-question" />
                  </el-tooltip>
                </span>
                <el-input clearable
                          :maxlength="20"
                          v-model="form.sortByCategory"
                          placeholder="请输入排序值" />
              </el-form-item>
              <!-- 提交图片 -->
              <el-form-item label="上传图片:"
                            prop="categoryImages">
                <el-upload action="#"
                           :on-exceed="exceedFn"
                           list-type="picture-card"
                           :file-list="fileList"
                           :limit="1"
                           :on-change="
                    (files, fileList) => handleFileChange(files, fileList)
                  "
                           :auto-upload="false">
                  <i slot="default"
                     class="el-icon-plus"></i>
                  <div slot="file"
                       slot-scope="{ file }">
                    <img class="el-upload-list__item-thumbnail"
                         :src="file.url"
                         alt="" />
                    <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-preview"
                            @click="handlePictureCardPreview()">
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <span class="el-upload-list__item-delete"
                            @click="handleDownload(file)">
                        <i class="el-icon-download"></i>
                      </span>
                      <span class="el-upload-list__item-delete"
                            @click="handleRemove(file)">
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
                </el-upload>
              </el-form-item>
              <el-form-item label="展示状态:"
                            prop="notShow">
                <el-switch v-model="form.notShow"
                           :active-value="1"
                           :inactive-value="2">
                </el-switch>
              </el-form-item>
            </el-form>
            <div class="drawer__footer">
              <el-button round
                         type="plain"
                         @click="handleClose"
                         size="medium">返回</el-button>
              <el-button type="primary"
                         round
                         :loading="loading"
                         size="medium"
                         @click="save">确定</el-button>
            </div>
          </div>
        </el-card>
      </div>
    </el-drawer>
    <!-- 图片预览 -->
    <el-image-viewer v-if="viewerVisible"
                     style="z-index: 9999"
                     :on-close="closeViewer"
                     :url-list="imgViewArr" />
  </div>
</template>

<script>
import ElImageViewer from 'element-ui/packages/image/src/image-viewer';
import { getToken } from '@/utils/token-util';
import {
  userOssSignature,
  qnyOssSignature
} from '@/api/creatCenter/material';
import { storageConfigDetail } from '@/api/storageInfo/index';

import axios from 'axios';
import {
  siteCategoriesInsert,
  siteCategoriesList,
  siteCategoriesModify,
  siteCategoriesDetail
} from '@/api/serviceManagement/categoriesList';

export default {
  name: 'pictureEdit',
  components: { ElImageViewer },
  props: {
    drawerEditBoolen: {
      type: Boolean,
      default: false
    },
    // 修改回显的数据
    data: Object
  },
  data () {
    const categoryImages = (rule, value, callback) => {
      if (!this.form.categoryImages) {
        callback(new Error('请上传图片'));
      } else {
        callback();
      }
    };
    const DEFAULT_FORM = {
      // 分类名称
      classificationName: '',
      //   分类图片
      categoryImages: '',
      // 排序号
      sortByCategory: '',
      // 是否展示状态
      notShow: 1,
      // 站点id
      siteId: this.$store.state.site.info.id
    };
    return {
      storageMode: '',
      options: [],
      imageUrl: '',
      imgViewArr: [],
      viewerVisible: false,
      // 表单数据
      form: { ...DEFAULT_FORM },
      dialogImageUrl: '',
      fileList: [],
      dialogVisible: false,
      // 表单验证规则
      rules: {
        classificationName: [
          {
            required: true,
            message: '请输入分类名称',
            trigger: 'blur'
          }
        ],
        notShow: [
          {
            required: true,
            message: '请输入是否展示状态',
            trigger: 'blur'
          }
        ],

        sortByCategory: [
          {
            required: true,
            message: '请输入排序值',
            trigger: 'blur'
          }
        ],
        // 站点 图片上传
        categoryImages: [
          { required: true, validator: categoryImages, trigger: 'change' }
        ]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      showChoose: false
    };
  },
  activated () {
    this.storageConfig();
  },
  methods: {
    // 获取存储配置
    async storageConfig () {
      const res = await storageConfigDetail();

      //   console.log(res.storageMode);

      this.storageMode = res?.storageMode;
    },
    // 关闭查看器
    closeViewer () {
      this.viewerVisible = false;
    },
    // 下载图片
    handleDownload (file) {
      window.open(file.url);
    },
    // 删除图片
    handleRemove () {
      this.fileList = [];
      this.imageUrl = '';
    },
    //  图片上传个数超过限制
    exceedFn () {
      this.$message({
        message: '图片上传已达到上限,请删除后再上传',
        type: 'warning'
      });
    },
    // 关闭抽屉
    handleClose () {
      console.log('查看详情');
      this.$emit('update:drawerEditBoolen', false);
    },
    async handleFileChange (file, fileList) {
      console.log(this.storageMode);
      if (this.storageMode == 2) {
        this.aliFn(file, fileList);
      } else if (this.storageMode == 3) {
        this.qnyFn(file, fileList);
      }
    },
    // 阿里云
    async aliFn (file, fileList) {
      this.loading = true;
      const res = await userOssSignature();
      let files = file.raw;
      let filename = file.name;
      let markIndex = filename.lastIndexOf('.');
      let suffix = filename.substring(markIndex);
      let date = new Date().getTime();
      // 构建请求参数
      let param = new FormData();
      param.append('key', date + suffix);
      param.append('policy', res.policy);
      param.append('OSSAccessKeyId', res.accessId);
      param.append('success_action_status', '200');
      // param.append("callback",  this.data.callback)     //回调（not)
      param.append('signature', res.signature);
      param.append('file', files, files.name);
      param.append('success_action_status', '200');
      let config = {
        headers: {
          'Access-Control-Allow-Origin': '*',
          'x-oss-callback-Authorization': getToken()
        }
      };
      console.log('suffix', suffix);

      let result = await axios.post(res.host, param, config);
      let url = res.host + '/' + date + suffix;
      console.log(url);
      this.imageUrl = url;
      this.loading = false;
    },
    async qnyFn (file, fileList) {
      this.loading = true;
      console.log(file, fileList);

      let files = file.raw;
      console.log(files);
      //   // 构建请求参数
      let param = new FormData();

      param.append('file', files, files.name);
      param.append('getsize', files.size);
      param.append('getContentType', files.type);
      param.append('getoriginalfilename', files.name);
      param.append('getName', files.name);

      const res = await qnyOssSignature(param);
      console.log(res.url);
      this.imageUrl = res.url;
      console.log('上传图片成功=======', res);
      this.loading = false;
    },
    // 点击按钮预览图片
    handlePictureCardPreview () {
      const imgStr = this.imageUrl;
      console.log(imgStr);
      if (imgStr.length) {
        if (imgStr.includes(',')) {
          console.log('字符串中包含逗号');
          // 包含的进行slice(',') 分割

          this.imgViewArr = imgStr.split(',').map((item) => item.trim());
        } else {
          console.log('字符串中不包含逗号');
          this.imgViewArr = imgStr.split();
        }

        this.viewerVisible = true;
      } else {
        this.$message({
          message: '没有上传图片无法进行预览',
          type: 'warning'
        });
      }
    },
    /* 保存编辑 */
    save () {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return false;
        }
        this.form.categoryImages = this.imageUrl;
        const data = {
          ...this.form
        };
        console.log(data);
        this.loading = true;

        const saveOrUpdate = this.isUpdate
          ? siteCategoriesModify
          : siteCategoriesInsert;
        saveOrUpdate(data)
          .then((msg) => {
            console.log(msg);
            this.loading = false;
            this.$message.success(msg);
            if (!this.isUpdate) {
              this.$router.go(0);
            }
            this.handleClose();
            this.$emit('done');
          })
          .catch((e) => {
            this.loading = false;
            this.$message.error(e.message);
          });
      });
    }
    /* 更新visible */
  },
  watch: {
    drawerEditBoolen (visible) {
      this.$nextTick(() => {
        if (visible) {
          console.log(this.data);
          if (this.data) {
            this.form.id = '';
            this.$util.assignObject(this.form, {
              ...this.data
            });
            if (this.form.categoryImages) {
              this.imageUrl = this.form.categoryImages;
              let markIndex = this.form.categoryImages.lastIndexOf('.');
              let suffix = this.form.categoryImages.substring(markIndex);
              if (!this.fileList.length) {
                this.fileList.push({
                  name: suffix,
                  url: this.form.categoryImages
                });
                console.log(this.fileList);
              }
            } else {
              this.fileList = [];
            }
            this.isUpdate = true;
          } else {
            this.isUpdate = false;
          }
        } else {
          this.$nextTick(() => {
            this.$refs['form'].resetFields();
            console.log(this.form);
          });
          this.fileList = [];
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
.foodsDiv div {
  margin-left: 20px;
  margin-top: 10px;
}
.height83 {
  height: 83vh;
}
.hLabel {
  margin: 10px 0 20px;
  font-weight: 700;
  &::before {
    content: '';
    display: inline-block;
    vertical-align: top;

    margin-right: 5px;
    height: 23px;
    width: 6px;
    background-color: #1e6ceb;
  }
}
.drawer__footer {
  display: flex;
  justify-content: flex-start;
  margin-left: 15px;
}
</style>
